extends Node2D

const CHICKEN = preload("res://scenes/entities/enemy/chicken（奖励关小鸡）/chicken.tscn")

@onready var collision_shape_2d: CollisionShape2D = %CollisionShape2D
@onready var tele_portation_point: Node2D = %TelePortationPoint

@export var spawn_interval      : float = 1.0          # 每隔几秒刷一次
@export var spawn_duration      : float = 15.0         # 持续刷新的总时长
@export var chickens_per_wave   : int   = 3            # 一次刷几只
@export var spawn_rect : Rect2
# ↑ spawn_rect 以本节点为原点；把节点放到场景中央即可把矩形放到想要的位置。 

var _elapsed : float = 0.0         # 已经过去的时间
var _timer   : Timer               # 用来按间隔触发刷怪
var _rectangleShape2D: RectangleShape2D

func _ready() -> void:
	EventBus.subscribe("to_des", on_to_des)

func _on_timer_timeout() -> void:
	if _elapsed >= spawn_duration:
		EventBus.push_event("show_time", [int(spawn_duration - _elapsed), false])
		EventBus.push_event("to_des", ["main_scene"])
		# 发送杀鸡结束事件
		EventBus.push_event("kill_chicken_end")
		_elapsed = 0
		_timer.stop()
		_timer.queue_free()
		return

	for i in chickens_per_wave:
		var chick: ChickenEnemy = CHICKEN.instantiate()
		chick.global_position = _get_random_point_in_rect()
		get_tree().current_scene.add_child(chick)
		
	_elapsed += spawn_interval
	EventBus.push_event("show_time", [int(spawn_duration - _elapsed), true])
	
func _get_random_point_in_rect() -> Vector2:
	# 返回 spawn_rect（相对本节点坐标系）里的随机点
	var local_pos := Vector2(
		randf_range(spawn_rect.position.x, spawn_rect.position.x + spawn_rect.size.x),
		randf_range(spawn_rect.position.y, spawn_rect.position.y + spawn_rect.size.y)
	)
	return local_pos


func on_to_des(_name):
	if _name == "kill_chicken":
		Utils.player.global_position = tele_portation_point.global_position
		RaffleManager.kill_chicken_count -= 1
		randomize()
		_timer = Timer.new()
		_timer.wait_time = spawn_interval
		_timer.one_shot  = false
		_timer.timeout.connect(_on_timer_timeout)
		add_child(_timer)
		_timer.start()
		_rectangleShape2D = collision_shape_2d.shape
		spawn_rect = Rect2(
			Vector2(collision_shape_2d.global_position - _rectangleShape2D.size / 2),
			Vector2(_rectangleShape2D.size)
		)
		
		# 发送杀鸡开始事件
		EventBus.push_event("kill_chicken_start")
		
